let title,user,time,todolist

pAjax({ url:'https://api.iynn.cn/mock?t=2'  })
      .then(res =>{
        todolist=JSON.parse(localStorage.getItem('todolist'))||JSON.parse(res).data
        document.querySelector('.add>button').addEventListener('click',addHandler)
        document.querySelector('table>tbody').addEventListener('click',clickHandler)
        document.querySelector('.mask').addEventListener('click',maskHandler)
        newtable()
        // console.log(todolist)
      } )
function addHandler(e){
  let id=todolist[todolist.length-1].id-0+1
  title=document.querySelector('.title').value
  user=document.querySelector('.user').value
  time=document.querySelector('.time').value
  // console.log(todolist)
  todolist.push({date:time,title,user,id})
  localStorage.setItem('todolist',JSON.stringify(todolist))
  newtable()
  console.log(todolist)
}
function newtable(){
  let tbody=document.querySelector('table>tbody')
  tbody.innerHTML=""
  todolist.forEach(item => {
    tbody.innerHTML+=`<tr>
    <td>${item.id}</td>
    <td>${item.title}</td>
    <td>${item.user}</td>
    <td>${item.date}</td>
    <td><button class="change" data-id='${item.id}'>修改</button><button class="del" data-id='${item.id}'>删除</button></td>
</tr>`
  });
}
function clickHandler(e){
  if(e.target.className==='del'){
    let id=e.target.getAttribute('data-id')-0
    todolist=todolist.filter(function(item){
      return (item.id-0)===id?false:true
    })
    localStorage.setItem('todolist',JSON.stringify(todolist))
    newtable()
  }
  if(e.target.className==='change'){
    let id=e.target.getAttribute('data-id')-0
    let obj=todolist.filter(function(item){
      return (item.id-0)===id
    })[0]
    console.log(todolist)
    // console.log(obj)
    document.querySelector('.changetitle').value=obj.title
    document.querySelector('.changeuser').value=obj.user
    document.querySelector('.changedate').value=obj.date
    document.querySelector('.newdata').setAttribute('data-id',id)
    document.querySelector("#mask").style.display='block'

  }
}
function maskHandler(e){
  if(e.target.className==='esc'){
    document.querySelector("#mask").style.display='none'
  }
  if(e.target.className==='newdata'){
    let id=e.target.getAttribute('data-id')-0
    todolist=todolist.map(item=>{
      return (item.id-0)===id?{
        id:id,
        title:document.querySelector('.changetitle').value,
        user:document.querySelector('.changeuser').value,
        date:document.querySelector('.changedate').value
      }:item
    })
    localStorage.setItem('todolist',JSON.stringify(todolist))
    document.querySelector("#mask").style.display='none'
    newtable()
  }
}